#include "general_config.h"
#include "app.h"
#include "TFT_LCD.h"
#include "stdio.h"
#include "Beep.h"
#include "picture.h"

warn_para_t warn_para;

volatile uint8_t warn_button = 2; // 报警状态，2运行，4取消

volatile uint8_t warn_state = 0; // 低压报警，0不报警，1第一种报警，2第二种报警

volatile uint8_t warn_state_flg = 0; // 低压报警，0不报警，1第一种报警，2第二种报警

uint8_t stop_flg = 0;
// volatile uint8_t Beep_one_flg = 0;
volatile uint8_t Charge_Complete_Flag; // 0：未完成，1：已完成
uint16_t Warning_time_s = 0;		   // Warning_time_m; //单位秒，预警时间10分钟 //目前两分钟
uint16_t Power_off_time = 0;
static uint16_t Low_press_time = 0;	   // Warning_time_m; //单位秒，预警时间10分钟 //目前两分钟

bool system_started = FALSE;
// bool pressure_normal_flag = false;
// uint32_t low_pressure_counter = 0;

// static uint16_t Warning_low_time = 0;//Warning_time_m; //单位秒，预警时间10分钟 //目前两分钟

volatile uint8_t Red_Flg_test1 = 0; // 红灯闪烁标志位
uint8_t RED_FIG = 0;

volatile uint8_t Yellow_Flg_test1 = 0; // 黄灯闪烁标志位
uint8_t Yellow_FIG = 0;

// 故障检查
volatile uint32_t timer_2min;
volatile uint8_t Motor_flg_test1;
// volatile uint8_t trigger_count = 0;
volatile bool MOTOR_START;

struct
{
	uint8_t CheckTimeFlag;
	int8_t CheckTimeout;
	uint16_t CheckTimeCount;
	uint64_t AddTime;
	uint64_t StandardTime;
} calibration;

uint8_t pressTimeoutCnt;
uint8_t UartSendDelay;
uint8_t rx2_frame_OK;
uint8_t rx1_frame_OK; // 压力垫数据接收完成
uint8_t rx2_buff[rx2_buffersize];
uint8_t rx1_buff[rx1_buffersize]; // 压力垫接收数据
uint8_t PressValue_buff[PressValue_buffersize];
uint8_t PressProfile_buff[32][16];
uint16_t rx2count;
uint16_t rx1count;
BYTE_t PumpStatus;

uint8_t NewWarn_Flag = 0;
uint16_t cycle_LeftTime, turn_LeftTime;	 // s
uint32_t turn_keeptime, nowave_keeptime; // s
set_para_t SettingPARA, CurrentPARA;
Warning_Flag_t Warning_State;
extern flag_t Flag;
//-----------------------------------------------------------------//
// 函数名称： uint16_t calc_airpress()
// 函数功能： 计算空气气压值   ((hight*hight)/weight)*0.379+3.835=13.12
// 返 回 值： 气压值temp        初始值是13.12
//-----------------------------------------------------------------//
uint16_t calc_airpress()
{
	double temp;
	if (MODE_NURSE == CurrentPARA.mode) // 护理模式
		return max_press;				// 气压16000
	if (MODE_SIT == CurrentPARA.mode)	// 静态模式
		return sit_press;				// 气压15000
	/*
		temp=(double)(CurrentPARA.hight*CurrentPARA.hight)/10000.0;
		temp=((double)(CurrentPARA.weight)/temp*0.429+3.835)*100;
	*/
	temp = (double)3.835 + BMI * (double)0.379; // 气垫床压力(kpa)=3.835+BMI×0.379
	temp = temp * (double)300.0 / (double)press_ad_exchage;

	if (temp > max_press)
		temp = max_press;
	else if (temp < min_press)
		temp = min_press;
	return (uint16_t)temp; // 返回气压值
}
//-----------------------------------------------------------------//
// 函数名称：
// 函数功能：
// 返 回 值：
//-----------------------------------------------------------------//
void WIFI_INIT()
{
	rcu_periph_clock_enable(RCU_GPIOB); // PB12推挽输出  WIFI使能位
	gpio_init(GPIOB, GPIO_MODE_OUT_PP, GPIO_OSPEED_50MHZ, GPIO_PIN_12);
	gpio_bit_reset(GPIOB, GPIO_PIN_12); //
	delay_1ms(200);
	gpio_bit_set(GPIOB, GPIO_PIN_12);
}

// void usart1_dma_reset(void)
//{
// dma_parameter_struct dma_init_struct;
// }

// dma配置
void usart_dma_config(void)
{
	dma_parameter_struct dma_init_struct;
	/* enable DMA0 */
	rcu_periph_clock_enable(RCU_DMA0);
	/* deinitialize DMA channel5(USART1 rx) */
	dma_deinit(DMA0, DMA_CH5);
	dma_init_struct.direction = DMA_PERIPHERAL_TO_MEMORY;
	dma_init_struct.memory_addr = (uint32_t)rx1_buff;
	dma_init_struct.memory_inc = DMA_MEMORY_INCREASE_ENABLE;
	dma_init_struct.memory_width = DMA_MEMORY_WIDTH_8BIT;
	dma_init_struct.number = 520;
	dma_init_struct.periph_addr = ((uint32_t)0x40000000U) + 0x00004400U + 0x00000004U; // USART_DATA(USART1);
	dma_init_struct.periph_inc = DMA_PERIPH_INCREASE_DISABLE;
	dma_init_struct.periph_width = DMA_PERIPHERAL_WIDTH_8BIT;
	dma_init_struct.priority = DMA_PRIORITY_ULTRA_HIGH;
	dma_init(DMA0, DMA_CH5, &dma_init_struct);

	dma_transfer_number_config(DMA0, DMA_CH5, rx1_buffersize);
	/* configure DMA mode */
	dma_circulation_enable(DMA0, DMA_CH5);
	dma_memory_to_memory_disable(DMA0, DMA_CH5);

	/* enable DMA0 channel4 transfer complete interrupt */
	//    dma_interrupt_enable(DMA0, DMA_CH5, DMA_INT_FTF);

	/* enable DMA channel */
	dma_channel_enable(DMA0, DMA_CH5);
	/* USART DMA enable for  reception */
	usart_dma_receive_config(USART1, USART_DENR_ENABLE);

	/* wait until USART0 RX DMA0 channel receive complete */
	//    while(RESET == dma_flag_get(DMA0, DMA_CH5, DMA_FLAG_FTF)){
	//    }
}

// 压力垫
void usart1_config()
{
	/* enable GPIO clock */
	rcu_periph_clock_enable(RCU_GPIOA);

	/* enable USART clock */
	rcu_periph_clock_enable(RCU_USART1);

	/* connect port to USARTx_Tx */
	gpio_init(GPIOA, GPIO_MODE_AF_PP, GPIO_OSPEED_50MHZ, GPIO_PIN_2);

	/* connect port to USARTx_Rx */
	gpio_init(GPIOA, GPIO_MODE_IN_FLOATING, GPIO_OSPEED_50MHZ, GPIO_PIN_3);

	/* USART configure */
	usart_deinit(USART1);
	usart_baudrate_set(USART1, 115200U);
	usart_word_length_set(USART1, USART_WL_8BIT);
	usart_stop_bit_set(USART1, USART_STB_1BIT);
	usart_parity_config(USART1, USART_PM_NONE);
	usart_hardware_flow_rts_config(USART1, USART_RTS_DISABLE);
	usart_hardware_flow_cts_config(USART1, USART_CTS_DISABLE);
	usart_receive_config(USART1, USART_RECEIVE_ENABLE);
	//    usart_transmit_config(USART1, USART_TRANSMIT_ENABLE);

	/* USART interrupt configuration */
	nvic_irq_enable(USART1_IRQn, 1, 1);
	/* enable USART2 IDLE interrupt */
	usart_interrupt_enable(USART1, USART_INT_IDLE);
	usart_enable(USART1);

	//		usart_interrupt_flag_clear(USART1, USART_INT_FLAG_IDLE);
}

// wifi
void usart2_config()
{
	/* enable GPIO clock 启用GPIO时钟*/
	rcu_periph_clock_enable(RCU_GPIOB);

	/* enable USART clock 启用USART时钟*/
	rcu_periph_clock_enable(RCU_USART2);

	/* connect port to USARTx_Tx  初始化GPIO   上拉输出 */
	gpio_init(GPIOB, GPIO_MODE_AF_PP, GPIO_OSPEED_50MHZ, GPIO_PIN_10);

	/* connect port to USARTx_Rx    悬浮输入*/
	gpio_init(GPIOB, GPIO_MODE_IN_FLOATING, GPIO_OSPEED_50MHZ, GPIO_PIN_11);

	/* USART configure */
	usart_deinit(USART2);									   // 初始化
	usart_baudrate_set(USART2, 115200U);					   // 设置波特率
	usart_word_length_set(USART2, USART_WL_8BIT);			   // 字节长度8bit
	usart_stop_bit_set(USART2, USART_STB_1BIT);				   // 停止位设置
	usart_parity_config(USART2, USART_PM_NONE);				   // 简要配置USART奇偶校验
	usart_hardware_flow_rts_config(USART2, USART_RTS_DISABLE); // 禁用RTS
	usart_hardware_flow_cts_config(USART2, USART_CTS_DISABLE); // 禁用RTS
	usart_receive_config(USART2, USART_RECEIVE_ENABLE);		   // 启用USART接收
	usart_transmit_config(USART2, USART_TRANSMIT_ENABLE);	   // 启用USART传输
	usart_enable(USART2);									   // 启用USART2

	/* USART interrupt configuration */
	nvic_irq_enable(USART2_IRQn, 0, 0); // 设置的抢占优先级  设置的子优先级
	/* enable USART2 receive interrupt 读取数据缓冲区非空中断和超限错误中断 */
	usart_interrupt_enable(USART2, USART_INT_RBNE); // 启用USART中断
}

// 定时器溢出时间计算方法:Tout=((arr+1)*(psc+1))/Ft us.
void timer5_init(uint16_t arr, uint16_t psc)
{
	timer_parameter_struct timer_initpara;
	rcu_periph_clock_enable(RCU_TIMER5);
	timer_deinit(TIMER5);

	timer_initpara.prescaler = psc; /* 时钟预分频系数 */
	timer_initpara.period = arr;	/* 自动重装载值 */
	timer_init(TIMER5, &timer_initpara);
	timer_enable(TIMER5);

	nvic_irq_enable(TIMER5_IRQn, 3, 3);			  /* 中断设置，抢占优先级3，子优先级3 */
	timer_interrupt_enable(TIMER5, TIMER_INT_UP); /* 使能更新中断 */
}

void usart2send(uint8_t *s, uint16_t lenth)
{
	uint16_t i;
	for (i = 0; i < lenth; i++)
	{
		usart_data_transmit(USART2, (uint8_t)s[i]);
		while (RESET == usart_flag_get(USART2, USART_FLAG_TBE))
			;
	}
}
// 数据和长度

//-----------------------------------------------------------------//
// 函数名称： uint32_t OPENBL_CRC32_MPEG_2(uint8_t *data, uint32_t length)
// 函数功能： CRC校验
// 返 回 值： 32位数据CRC的值
//-----------------------------------------------------------------//
uint32_t OPENBL_CRC32_MPEG_2(uint8_t *data, uint32_t length)
{
	uint32_t i;
	uint32_t crc = 0xffffffff, j = 0;

	while ((length--) != 0)
	{
		crc ^= (uint32_t)data[j] << 24;
		j++;
		for (i = 0; i < 8; ++i)
		{
			if ((crc & 0x80000000) != 0)
			{
				crc = (crc << 1) ^ 0x04C11DB7;
			}
			else
			{
				crc <<= 1;
			}
		}
	}
	return crc;
}
//-----------------------------------------------------------------//
// 函数名称： uint32_t OPENBL_CRC32_MPEG_2(uint8_t *data, uint32_t length)
// 函数功能： CRC校验
// 返 回 值： 32位数据CRC的值
//-----------------------------------------------------------------//
void CRC_usart2send(uint8_t *data, uint32_t length)
{
	uint32_t crc_temp, i;
	uint8_t crc[4];

	crc_temp = OPENBL_CRC32_MPEG_2(data, length);
	crc[0] = (uint8_t)crc_temp;
	crc[1] = (uint8_t)(crc_temp >> 8);
	crc[2] = (uint8_t)(crc_temp >> 16);
	crc[3] = (uint8_t)(crc_temp >> 24);
	for (i = 0; i < length; i++)
	{
		usart_data_transmit(USART2, (uint8_t)data[i]);
		while (RESET == usart_flag_get(USART2, USART_FLAG_TBE))
			;
	}
	for (i = 0; i < 4; i++)
	{
		usart_data_transmit(USART2, (uint8_t)crc[i]);
		while (RESET == usart_flag_get(USART2, USART_FLAG_TBE))
			;
	}
}
//-----------------------------------------------------------------//
// 函数名称： void Pump1Work(uint16_t pressure)
// 函数功能：
// 返 回 值：
//-----------------------------------------------------------------//
void Pump1Work(uint16_t pressure)
{
	uint16_t temp;
	temp = ADC_AirPress1();

	if (temp) // AD值出来后
	{
		if (temp < 500)
			temp = 12 * temp;
		else
			temp = 10 * temp + 2200; // AD值是1相当于10倍+2200帕斯卡
		//			usart_data_transmit(USART2,temp>>8);
		//			while(RESET == usart_flag_get(USART2, USART_FLAG_TBE));
		//			usart_data_transmit(USART2,temp);
		//			while(RESET == usart_flag_get(USART2, USART_FLAG_TBE));

		if (temp >= pressure + 100) // 充气完成
		{
			Pump1Off;
		}
		else if (temp < pressure) // 充气未完成
		{
			Pump1ON;
		}
		CurrentPARA.air_pressure = temp;
		// CurrentPARA.air_pressure=temp*11;//AD值是1相当于11帕斯卡
	}
}
//-----------------------------------------------------------------//
//// 函数名称：
//// 函数功能： 通过ADC采集的气压值确定是否进行工作
//// 输入参数： 无
//// 输出参数： 无
//// 返 回 值：
////-----------------------------------------------------------------//
// void Pump2Work(uint16_t pressure)
//{
//	uint16_t temp;
//	temp = ADC_AirPress2();
//	if (temp)
//	{
//		if (temp < 500)
//			temp = 12 * temp;
//		else
//			temp = 10 * temp + 2200; // AD值是1相当于10倍+2200帕斯卡
//		if (temp >= pressure + 100)
//		{
//			Pump2Off;
//		}
//		else if (temp < pressure)
//		{
//			Pump2ON;
//		}
//		//		CurrentPARA.air_pressure=temp;
//	}
// }

//-----------------------------------------------------------------//
// 函数名称：翻身
// 函数功能： 通过ADC采集的气压值确定是否进行工作
// 输入参数： 无
// 输出参数： 无
// 返 回 值：
//-----------------------------------------------------------------//
// void Pump2Work(uint16_t pressure)
// {
// 	uint16_t temp;
// 	temp = ADC_AirPress2();
// 	if (temp)
// 	{
// 		if (temp < 500)
// 			temp = 12 * temp;
// 		else
// 			temp = 10 * temp + 2200; // AD值是1相当于10倍+2200帕斯卡
// 		if (temp >= pressure + 100)//充气完成
// 		{
// 			Pump2Off;
// 			if (temp >= pressure - 2500)//充气完成
// 			{
// 				CurrentPARA.turn_status=2;
// 			}
// 		}
// 		else if (temp < pressure)
// 		{
// 			Pump2ON;
// 			if((temp<pressure)&&(temp>=1500))//充气过程中
// 			{
// 				CurrentPARA.turn_status=1;
// 			}
// 			else if((0<temp)&&(temp<1500))//未充气或者刚开始充
// 			{
// 				CurrentPARA.turn_status=0;
// 			}
// 		}
// 		//		CurrentPARA.air_pressure=temp;
// 	}
// }

void NVIC_CoreReset(void)
{
	__DSB(); // 置位VECTRESET
	SCB->AIRCR = ((0x5FA << SCB_AIRCR_VECTKEY_Pos) |
				  (SCB->AIRCR & SCB_AIRCR_PRIGROUP_Msk) |
				  SCB_AIRCR_VECTRESET_Msk);
	__DSB();
	while (1)
		;
}
//-----------------------------------------------------------------//
// 函数名称：
// 函数功能：
// 返 回 值：
//-----------------------------------------------------------------//
void do_upgrade(void)
{
	__disable_irq();
	fmc_unlock();
	fmc_page_erase(FLASH_DATA_FLAG_ADDR);
	fmc_halfword_program(FLASH_DATA_FLAG_ADDR, FLASH_DATA_FLAG);
	fmc_lock();
	NVIC_SystemReset();
}

char Web_Control_Flag = 0; // NOTE: Web 端控制位 ，接收数据置为2
/**
 * @function: ReceiveHdl
 * @brief: ESP32->GD32
 * @return {*}
 * @author: lzc
 */
void ReceiveHdl()
{
	uint32_t crcCal;
	uint8_t crcGet[4];
	if (rx2_frame_OK) // 接受esp32程序完成
	{
		if (0x0A == rx2_buff[4]) // wifi模块是否连上MQTT
		{
			Flag.mqtt_conected = rx2_buff[5];
			rx2count = 0;
			rx2_frame_OK = 0;
			return;
		}
		else if (0x0B == rx2_buff[4]) // wifi模块是否连上路由器
		{
			Flag.route_conected = rx2_buff[5];
			rx2count = 0;
			rx2_frame_OK = 0;
			return;
		}
		else if (0x0C == rx2_buff[4]) // 待配网状态  开始配网
		{
			Flag.set_password = rx2_buff[5];
			rx2count = 0;
			rx2_frame_OK = 0;
			return;
		}
		else if (0x0D == rx2_buff[4]) // 需发送固件信息
		{
			Flag.SendFWInfo = rx2_buff[5];
			rx2count = 0;
			rx2_frame_OK = 0;
			return;
		}
		// 获取CRC
		crcGet[0] = rx2_buff[rx2count - 4];
		crcGet[1] = rx2_buff[rx2count - 3];
		crcGet[2] = rx2_buff[rx2count - 2];
		crcGet[3] = rx2_buff[rx2count - 1];
		crcCal = OPENBL_CRC32_MPEG_2(rx2_buff, rx2count - 4);

		if (*(__IO uint32_t *)crcGet == crcCal) // CRC校验合格
		{
			if (0x20 == rx2_buff[4]) // 时间校准
			{
				calibration.StandardTime = (uint64_t)(rx2_buff[5]) << 0;
				calibration.StandardTime |= (uint64_t)(rx2_buff[6]) << 8;
				calibration.StandardTime |= (uint64_t)(rx2_buff[7]) << 16;
				calibration.StandardTime |= (uint64_t)(rx2_buff[8]) << 24;
				calibration.StandardTime |= (uint64_t)(rx2_buff[9]) << 32;
				calibration.StandardTime |= (uint64_t)(rx2_buff[10]) << 40;
				calibration.StandardTime |= (uint64_t)(rx2_buff[11]) << 48;
				calibration.StandardTime |= (uint64_t)(rx2_buff[12]) << 56;
				calibration.AddTime = 0;
				calibration.CheckTimeout = -1;
				calibration.CheckTimeFlag = 0;
				calibration.CheckTimeCount = CheckTimeDelay;
				Flag.SendDataOn = 1;
				rx2count = 0;
				rx2_frame_OK = 0;
				return;
			}
			if (0x10 == rx2_buff[4])
			{
				do_upgrade(); // 升级
			}
			//-----------------------正常业务数据
			// SettingPARA.powON = 0x01;
			SettingPARA.powON = rx2_buff[5];
			SettingPARA.hight = rx2_buff[6];
			SettingPARA.weight = rx2_buff[7];
			SettingPARA.mode = rx2_buff[8];
			SettingPARA.WaveCycle_lenth = rx2_buff[9];
			SettingPARA.turn_mode = rx2_buff[10];
			SettingPARA.TurnCycle_lenth = rx2_buff[11];
			Web_Control_Flag = 2;
			
			// 刷新 LCD的函数
			TFTLCD_Fill(bodongleftime_x, bodongleftime_y, bodongleftime_x + 180, bodongleftime_y + 24, MY_BLUE);

//			TFTLCD_Fill(fanshenleftime_x, fanshenleftime_y, fanshenleftime_x + 180, fanshenleftime_y + 24, MY_BLUE);
#if Pressure_Warning_Enable
			if (rx2count > 16)
			{
				NewWarn_Flag = 1;
				SettingPARA.Shoulder_Yellow_Pressure_Threshold = rx2_buff[12];
				SettingPARA.Shoulder_Yellow_OverTime_Threshold = rx2_buff[13];
				SettingPARA.Shoulder_Red_Pressure_Threshold = rx2_buff[14];
				SettingPARA.Shoulder_Red_OverTime_Threshold = rx2_buff[15];

				SettingPARA.Back_Yellow_Pressure_Threshold = rx2_buff[16];
				SettingPARA.Back_Yellow_OverTime_Threshold = rx2_buff[17];
				SettingPARA.Back_Red_Pressure_Threshold = rx2_buff[18];
				SettingPARA.Back_Red_OverTime_Threshold = rx2_buff[19];

				SettingPARA.Hip_Yellow_Pressure_Threshold = rx2_buff[20];
				SettingPARA.Hip_Yellow_OverTime_Threshold = rx2_buff[21];
				SettingPARA.Hip_Red_Pressure_Threshold = rx2_buff[22];
				SettingPARA.Hip_Red_OverTime_Threshold = rx2_buff[23];

				SettingPARA.Leg_Yellow_Pressure_Threshold = rx2_buff[24];
				SettingPARA.Leg_Yellow_OverTime_Threshold = rx2_buff[25];
				SettingPARA.Leg_Red_Pressure_Threshold = rx2_buff[26];
				SettingPARA.Leg_Red_OverTime_Threshold = rx2_buff[27];
			}
			else
			{
				NewWarn_Flag = 0;
			}
#endif
		}
		rx2count = 0;
		rx2_frame_OK = 0;
	}
}
//-----------------------------------------------------------------//
// 函数名称： 设置身高  体重
// 函数功能：
// 返 回 值：
//-----------------------------------------------------------------//
void SetDown()
{
	//-------------------------------开关机
	if (CurrentPARA.powON != SettingPARA.powON)
	{
		CurrentPARA.powON = SettingPARA.powON; // 开机
		if (0 == CurrentPARA.powON)
		{
			cycle_LeftTime = 0;
			turn_LeftTime = 0;
			Pump1Off;
			// Pump2Off;
			vave1_SetPosi = limit2;
			// vave2_SetPosi = limit4;
			CurrentPARA.air_column = 0;
			LCD_OFF();
		}
		else
		{
			LCD_ON();
			if (MODE_WAVE == CurrentPARA.mode)
			{
				if (3 == CurrentPARA.air_column) // 气柱
				{
					CurrentPARA.air_column = 1; // 哪条气柱充气
					vave1_SetPosi = limit1;
					//					vave2_SetPosi=2;
				}
			}
		}
	}
	//-------------------------------身高
	if ((CurrentPARA.hight != SettingPARA.hight) && (Flag.PageNO != page_hight))
	{
		if (SettingPARA.hight > hight_max)
			SettingPARA.hight = hight_max;
		else if (SettingPARA.hight < hight_min)
			SettingPARA.hight = hight_min;

		CurrentPARA.hight = SettingPARA.hight;

		BMI = (double)(CurrentPARA.hight * CurrentPARA.hight) / (double)10000.0;
		BMI = (double)(CurrentPARA.weight) / BMI;

		threshold = calc_airpress(); // 计算当前空气气压值
	}
	//-------------------------------体重
	if ((CurrentPARA.weight != SettingPARA.weight) && (Flag.PageNO != page_weight))
	{
		if (SettingPARA.weight > weight_max)
			SettingPARA.weight = weight_max;
		else if (SettingPARA.weight < weight_min)
			SettingPARA.weight = weight_min;

		CurrentPARA.weight = SettingPARA.weight;

		BMI = (double)(CurrentPARA.hight * CurrentPARA.hight) / (double)10000.0;
		BMI = (double)(CurrentPARA.weight) / BMI; // BMI等于体重除以身高的平方

		threshold = calc_airpress();
	}
	//--------------------------------波动、静态模式
	if (CurrentPARA.mode != SettingPARA.mode)
	{
		if (MODE_WAVE == SettingPARA.mode) // 波动模式
		{
			if (Flag.PageNO != page_wave)
			{
				CurrentPARA.mode = SettingPARA.mode;
				CurrentPARA.air_column = 2; // 设置更新后，立即更新阀位置
				vave1_SetPosi = limit3;

				nowave_keeptime = 0; // 波动持续时间清零
			}
		}
		else
		{
			if (Flag.PageNO != page_mode)
			{
				CurrentPARA.mode = SettingPARA.mode;
				cycle_LeftTime = 0;
				CurrentPARA.WaveCycle_lenth = 0;
				//			SettingPARA.WaveCycle_lenth=def_wavelenth;
				vave1_SetPosi = limit2;
				CurrentPARA.air_column = 3;

				nowave_keeptime = 0; // 波动持续时间清零
			}
		}
		threshold = calc_airpress();
		// if (threshold == 15000)
		// {

		// }
	}
	if (MODE_WAVE == CurrentPARA.mode && Flag.PageNO != page_wave)
	{
		if (SettingPARA.WaveCycle_lenth > WaveLenth_max)
			SettingPARA.WaveCycle_lenth = WaveLenth_max;
		else if (SettingPARA.WaveCycle_lenth < WaveLenth_min)
			SettingPARA.WaveCycle_lenth = WaveLenth_min;

		if (CurrentPARA.WaveCycle_lenth != SettingPARA.WaveCycle_lenth && Flag.PageNO != page_wave)
		{
			cycle_LeftTime = 60 * SettingPARA.WaveCycle_lenth; // 设置更新后，立即更新剩余交替时间
			CurrentPARA.WaveCycle_lenth = SettingPARA.WaveCycle_lenth;
		}
	}
}
//-----------------------------------------------------------------//
// 函数名称：
// 函数功能：
// 返 回 值：
//-----------------------------------------------------------------//
void bodystatus()
{
	uint16_t i;
	uint32_t sum = 0;
	for (i = 1; i <= 1550; i++)
		sum += rx1_buff[i]; // 求和压力垫数据

	if (sum > 2500) // 离床InBedPress
	{
		CurrentPARA.inbed = 1;
	}
	else
	{
		CurrentPARA.inbed = 0;
	}
}
// void getPressprofile()
//{
//	if(0==rx1_frame_OK) return;
//	if((rx1count==516)/*&&(rx1_buff[0]==0xf0)&&(rx1_buff[515]==0xf7)*/)
//	{
//		memcpy(PressProfile_buff,&rx1_buff[2],512);
//
//	}
//	else
//	{
//		rx1_frame_OK=0;
//	}
//	memset(rx1_buff,0,rx1count);
//	dma_transfer_number_config(DMA0, DMA_CH5, rx1_buffersize);
//	dma_channel_enable(DMA0, DMA_CH5);
// }

// void PressValue_SendHandle()
//{
//	uint64_t CalibrationTime;
//	if(0==Flag.SendDataOn) return;//时间校准之前不发
//	if(0==rx1_frame_OK) return;
//
//	CalibrationTime=calibration.AddTime+calibration.StandardTime;
//
//	PressValue_buff[0]=0xA5;
//	PressValue_buff[1]=0x5A;
//	PressValue_buff[2]=(uint8_t)(525);
//	PressValue_buff[3]=(uint8_t)(525>>8);
//	PressValue_buff[4]=0x01;
//
//	PressValue_buff[5]=(uint8_t)(CalibrationTime>>0);
//	PressValue_buff[6]=(uint8_t)(CalibrationTime>>8);
//	PressValue_buff[7]=(uint8_t)(CalibrationTime>>16);
//	PressValue_buff[8]=(uint8_t)(CalibrationTime>>24);
//	PressValue_buff[9]=(uint8_t)(CalibrationTime>>32);
//	PressValue_buff[10]=(uint8_t)(CalibrationTime>>40);
//	PressValue_buff[11]=(uint8_t)(CalibrationTime>>48);
//	PressValue_buff[12]=(uint8_t)(CalibrationTime>>56);
//	memcpy(&PressValue_buff[13],PressProfile_buff,512);
////	usart2send(PressValue_buff,rx1count+32);
//	CRC_usart2send(PressValue_buff,525);
//}

/**
 * @function: Judge_Overpressure_Status
 * @brief:判断超压状态
 * @param {uint8_t} *data
 * @param {uint8_t} Single_Threshold
 * @param {uint8_t} Average_Threshold
 * @return {*}  x轴判断  腿部 肩部 头部等位置     y轴附近取点  最大值附近9个点
 * @author: lzc
 */
uint32_t SysTimeBase = 0;

// 定义数据范围
/*      压力垫数据图  总长60
			20				      10            10             20
	+--------------------------------------------------+
60  |                                                  |0
	|   <-------------------------------------------+  |
	|   |                                              |
	|   +------------------------------------------>   |
头  |                                              |   | 尾
	|   <------------------------------------------+   |
	|                                                  |
	|                                                  |
	|                                                  |25
	+--------------------------------------------------+
*/
// 合计25行,60列 —— 根据列来判断具体的位置
#define Pressure_Pad_Shoulder_Data_Range 20 // 肩部范围
#define Pressure_Pad_Back_Data_Range 10		// 背
#define Pressure_Pad_Hip_Data_Range 10		// 臀
#define Pressure_Pad_Leg_Data_Range 20		// 腿部

char Pressure_Pad_Shoulder_Flag = 0;
char Pressure_Pad_Back_Flag = 0;
char Pressure_Pad_Hip_Flag = 0;
char Pressure_Pad_Leg_Flag = 0;
// 0 0 0 0 表示没有异常  0
// 1 0 0 0 表示肩部超压  08
// 0 1 0 0 表示背部超压  04
// 1 1 0 0 表示肩部和背部超压  12

char Judge_Overpressure_Status(uint8_t *data,
							   uint8_t Shoulder_Single_Threshold, uint8_t Shoulder_Average_Threshold,
							   uint8_t Back_Single_Threshold, uint8_t Back_Average_Threshold,
							   uint8_t Hip_Single_Threshold, uint8_t Hip_Average_Threshold,
							   uint8_t Leg_Single_Threshold, uint8_t Leg_Average_Threshold)
{

	int PressValue_Count = -1;
	uint8_t Status = 0;
	uint16_t PressValue_Sum = 0; // 压力值总和

	// 一维数据转二维 16行10列
	uint8_t PressValue_Row = 0;	   // 行
	uint8_t PressValue_Column = 0; // 列

	uint8_t PressValue_Buffer[25][60];
	// 背部参数，行列以及其他
	uint8_t PressValue_Max_Back = 0;		// 背部最大值
	uint8_t PressValue_Max_Back_Row = 0;	// 行
	uint8_t PressValue_Max_Back_Column = 0; // 列
	uint8_t PressValue_Average_Back = 0;	// 背部平均值
	// 肩部参数，行列以及其他
	uint8_t PressValue_Max_Shoulder = 0;
	uint8_t PressValue_Max_Shoulder_Row = 0;
	uint8_t PressValue_Max_Shoulder_Column = 0;
	uint8_t PressValue_Average_Shoulder = 0;
	// 臀部参数，行列以及其他
	uint8_t PressValue_Max_Hip = 0;
	uint8_t PressValue_Max_Hip_Row = 0;
	uint8_t PressValue_Max_Hip_Column = 0;
	uint8_t PressValue_Average_Hip = 0;
	// 腿部参数，行列以及其他
	uint8_t PressValue_Max_Leg = 0;
	uint8_t PressValue_Max_Leg_Row = 0;
	uint8_t PressValue_Max_Leg_Column = 0;
	uint8_t PressValue_Average_Leg = 0;

	// 最多1500个超压点
	uint8_t PressValue_OverPressure_Point[1550][2] = {0};
	for (char i = 0; i < 25; i++) // 行
	{
		for (char j = 0; j < 60; j++) // 列
		{
			PressValue_Buffer[i][j] = data[60 * i + j]; // 一维数据转二维 25行60列

			// 记录单个超压数据点
			if ((PressValue_Buffer[i][j] > Leg_Single_Threshold) && (j < Pressure_Pad_Leg_Data_Range)) // 腿部
			{
				// 行
				PressValue_OverPressure_Point[PressValue_Count][0] = i; // 记录当时的列坐标
				// 列
				PressValue_OverPressure_Point[PressValue_Count][1] = j; // 记录当时的行坐标
				PressValue_Count++;										// 记录的几个点
			}

			// 记录超压数据点
			if ((PressValue_Buffer[i][j] > Hip_Single_Threshold) &&
				(j < (Pressure_Pad_Leg_Data_Range + Pressure_Pad_Hip_Data_Range) && j > (Pressure_Pad_Leg_Data_Range))) // 背部
			{
				// 行
				PressValue_OverPressure_Point[PressValue_Count][0] = i;
				// 列
				PressValue_OverPressure_Point[PressValue_Count][1] = j;
				PressValue_Count++;
			}

			// 记录超压数据点
			if ((PressValue_Buffer[i][j] > Back_Single_Threshold) &&
				(j < (Pressure_Pad_Back_Data_Range + Pressure_Pad_Leg_Data_Range + Pressure_Pad_Hip_Data_Range) && j > (Pressure_Pad_Leg_Data_Range + Pressure_Pad_Hip_Data_Range))) // 臀部
			{
				// 行
				PressValue_OverPressure_Point[PressValue_Count][0] = i;
				// 列
				PressValue_OverPressure_Point[PressValue_Count][1] = j;
				PressValue_Count++;
			}

			// 记录超压数据点
			if ((PressValue_Buffer[i][j] > Shoulder_Single_Threshold) &&
				(j < (Pressure_Pad_Back_Data_Range + Pressure_Pad_Shoulder_Data_Range + Pressure_Pad_Hip_Data_Range + Pressure_Pad_Leg_Data_Range) &&
				 (j > (Pressure_Pad_Back_Data_Range + Pressure_Pad_Leg_Data_Range + Pressure_Pad_Hip_Data_Range)))) // 腿部
			{
				// 行
				PressValue_OverPressure_Point[PressValue_Count][0] = i;
				// 列
				PressValue_OverPressure_Point[PressValue_Count][1] = j;
				PressValue_Count++;
			}
		}
	}

	// 寻找范围内的最大值
	for (char i = 0; i < PressValue_Count; i++)
	{
		if (PressValue_OverPressure_Point[i][1] < Pressure_Pad_Leg_Data_Range) // 部数据
		{
			PressValue_Row = PressValue_OverPressure_Point[i][0];	 // 行 记录行数据
			PressValue_Column = PressValue_OverPressure_Point[i][1]; // 列 记录列数据
			PressValue_Max_Leg_Row = PressValue_Row;
			PressValue_Max_Leg_Column = PressValue_Column;
			if (PressValue_Buffer[PressValue_Row][PressValue_Column] > PressValue_Max_Leg) // 一个一个比较确定最大值
			{
				PressValue_Max_Leg = PressValue_Buffer[PressValue_Row][PressValue_Column]; // 选取最大值点
			}
		}

		// 背部数据
		if (PressValue_OverPressure_Point[i][1] < (Pressure_Pad_Leg_Data_Range + Pressure_Pad_Hip_Data_Range) &&
			PressValue_OverPressure_Point[i][1] > Pressure_Pad_Leg_Data_Range)
		{
			PressValue_Row = PressValue_OverPressure_Point[i][0];	 // 行
			PressValue_Column = PressValue_OverPressure_Point[i][1]; // 列
			PressValue_Max_Hip_Row = PressValue_Row;
			PressValue_Max_Hip_Column = PressValue_Column;
			if (PressValue_Buffer[PressValue_Row][PressValue_Column] > PressValue_Max_Hip) // 一个一个比较确定最大值
			{
				PressValue_Max_Hip = PressValue_Buffer[PressValue_Row][PressValue_Column];
			}
		}

		// 臀部数据
		if (PressValue_OverPressure_Point[i][1] < (Pressure_Pad_Back_Data_Range + Pressure_Pad_Leg_Data_Range + Pressure_Pad_Hip_Data_Range) &&
			PressValue_OverPressure_Point[i][1] > Pressure_Pad_Hip_Data_Range + Pressure_Pad_Leg_Data_Range)
		{
			PressValue_Row = PressValue_OverPressure_Point[i][0];	 // 行
			PressValue_Column = PressValue_OverPressure_Point[i][1]; // 列
			PressValue_Max_Back_Row = PressValue_Row;
			PressValue_Max_Back_Column = PressValue_Column;
			if (PressValue_Buffer[PressValue_Row][PressValue_Column] > PressValue_Max_Back) // 一个一个比较确定最大值
			{
				PressValue_Max_Back = PressValue_Buffer[PressValue_Row][PressValue_Column];
			}
		}

		// 腿部数据
		if (PressValue_OverPressure_Point[i][1] < (Pressure_Pad_Back_Data_Range + Pressure_Pad_Shoulder_Data_Range + Pressure_Pad_Hip_Data_Range + Pressure_Pad_Leg_Data_Range) &&
			PressValue_OverPressure_Point[i][1] > Pressure_Pad_Leg_Data_Range + Pressure_Pad_Back_Data_Range + Pressure_Pad_Hip_Data_Range)
		{
			PressValue_Row = PressValue_OverPressure_Point[i][0];	 // 行
			PressValue_Column = PressValue_OverPressure_Point[i][1]; // 列
			PressValue_Max_Shoulder_Row = PressValue_Row;
			PressValue_Max_Shoulder_Column = PressValue_Column;
			if (PressValue_Buffer[PressValue_Row][PressValue_Column] > PressValue_Max_Shoulder) // 一个一个比较确定最大值
			{
				PressValue_Max_Shoulder = PressValue_Buffer[PressValue_Row][PressValue_Column];
			}
		}
	}

	// 根据当前各点位的最大值获取均值
	// 肩部数据取均值
	PressValue_Sum = 0;
	PressValue_Sum = PressValue_Buffer[PressValue_Max_Shoulder_Row - 1][PressValue_Max_Shoulder_Column - 1] +
					 PressValue_Buffer[PressValue_Max_Shoulder_Row - 1][PressValue_Max_Shoulder_Column] +
					 PressValue_Buffer[PressValue_Max_Shoulder_Row - 1][PressValue_Max_Shoulder_Column + 1] +
					 PressValue_Buffer[PressValue_Max_Shoulder_Row][PressValue_Max_Shoulder_Column - 1] +
					 PressValue_Buffer[PressValue_Max_Shoulder_Row][PressValue_Max_Shoulder_Column] +
					 PressValue_Buffer[PressValue_Max_Shoulder_Row][PressValue_Max_Shoulder_Column + 1] +
					 PressValue_Buffer[PressValue_Max_Shoulder_Row + 1][PressValue_Max_Shoulder_Column - 1] +
					 PressValue_Buffer[PressValue_Max_Shoulder_Row + 1][PressValue_Max_Shoulder_Column] +
					 PressValue_Buffer[PressValue_Max_Shoulder_Row + 1][PressValue_Max_Shoulder_Column + 1];
	PressValue_Average_Shoulder = PressValue_Sum / 9;

	// 背部数据取均值
	PressValue_Sum = 0;
	PressValue_Sum = PressValue_Buffer[PressValue_Max_Back_Row - 1][PressValue_Max_Back_Column - 1] +
					 PressValue_Buffer[PressValue_Max_Back_Row - 1][PressValue_Max_Back_Column] +
					 PressValue_Buffer[PressValue_Max_Back_Row - 1][PressValue_Max_Back_Column + 1] +
					 PressValue_Buffer[PressValue_Max_Back_Row][PressValue_Max_Back_Column - 1] +
					 PressValue_Buffer[PressValue_Max_Back_Row][PressValue_Max_Back_Column] +
					 PressValue_Buffer[PressValue_Max_Back_Row][PressValue_Max_Back_Column + 1] +
					 PressValue_Buffer[PressValue_Max_Back_Row + 1][PressValue_Max_Back_Column - 1] +
					 PressValue_Buffer[PressValue_Max_Back_Row + 1][PressValue_Max_Back_Column] +
					 PressValue_Buffer[PressValue_Max_Back_Row + 1][PressValue_Max_Back_Column + 1];
	PressValue_Average_Back = PressValue_Sum / 9;
	// 根据均值给状态

	// 背部数据取均值
	PressValue_Sum = 0;
	PressValue_Sum = PressValue_Buffer[PressValue_Max_Hip_Row - 1][PressValue_Max_Hip_Column - 1] +
					 PressValue_Buffer[PressValue_Max_Hip_Row - 1][PressValue_Max_Hip_Column] +
					 PressValue_Buffer[PressValue_Max_Hip_Row - 1][PressValue_Max_Hip_Column + 1] +
					 PressValue_Buffer[PressValue_Max_Hip_Row][PressValue_Max_Hip_Column - 1] +
					 PressValue_Buffer[PressValue_Max_Hip_Row][PressValue_Max_Hip_Column] +
					 PressValue_Buffer[PressValue_Max_Hip_Row][PressValue_Max_Hip_Column + 1] +
					 PressValue_Buffer[PressValue_Max_Hip_Row + 1][PressValue_Max_Hip_Column - 1] +
					 PressValue_Buffer[PressValue_Max_Hip_Row + 1][PressValue_Max_Hip_Column] +
					 PressValue_Buffer[PressValue_Max_Hip_Row + 1][PressValue_Max_Hip_Column + 1];
	PressValue_Average_Hip = PressValue_Sum / 9;
	// 根据均值给状态

	// 背部数据取均值
	PressValue_Sum = 0;
	PressValue_Sum = PressValue_Buffer[PressValue_Max_Leg_Row - 1][PressValue_Max_Leg_Column - 1] +
					 PressValue_Buffer[PressValue_Max_Leg_Row - 1][PressValue_Max_Leg_Column] +
					 PressValue_Buffer[PressValue_Max_Leg_Row - 1][PressValue_Max_Leg_Column + 1] +
					 PressValue_Buffer[PressValue_Max_Leg_Row][PressValue_Max_Leg_Column - 1] +
					 PressValue_Buffer[PressValue_Max_Leg_Row][PressValue_Max_Leg_Column] +
					 PressValue_Buffer[PressValue_Max_Leg_Row][PressValue_Max_Leg_Column + 1] +
					 PressValue_Buffer[PressValue_Max_Leg_Row + 1][PressValue_Max_Leg_Column - 1] +
					 PressValue_Buffer[PressValue_Max_Leg_Row + 1][PressValue_Max_Leg_Column] +
					 PressValue_Buffer[PressValue_Max_Leg_Row + 1][PressValue_Max_Leg_Column + 1];
	PressValue_Average_Leg = PressValue_Sum / 9;
	// 根据均值给状态

	if (PressValue_Average_Shoulder > Shoulder_Average_Threshold) // 肩部最大值均值
	{
		Status |= 0x08;
	}
	if (PressValue_Average_Back > Back_Average_Threshold) // 背部最大均值
	{
		Status |= 0x04;
	}
	if (PressValue_Average_Hip > Hip_Average_Threshold) // 臀部最大值均值
	{
		Status |= 0x02;
	}
	if (PressValue_Average_Leg > Leg_Average_Threshold) // 腿部最大均值
	{
		Status |= 0x01;
	}
	// #ifdef Pressure_Pad_Manufacturers_1500_Length
	// 	// 一维数据转二维 25行 60列
	// 	uint8_t PressValue_Row = 0;	   // 行
	// 	uint8_t PressValue_Column = 0; // 列
	// 	uint8_t PressValue_Count = 0;
	// 	uint8_t PressValue_Buffer[25][60];
	// 	// 更新数据
	// 	for (char i = 0; i < 25; i++) //行
	// 	{
	// 		for (char j = 0; j < 60; j++) //列
	// 		{
	// 			// 一维数据转二维 25行60列
	// 			PressValue_Buffer[i][j] = data[60 * i + j];
	// 		}
	// 	}
	// 	// ---------------------------Temp--------------------------------//
	// 	for (int i = 0; i < 25; i++)
	// 	{
	// 		for (int j = 0; j < 60; j++)
	// 		{
	// 			// 如果压力点数据较大则置位对应的标志位
	// 			if (PressValue_Buffer[i][j] > 25) //压力预警数据
	// 			{
	// 				if (j < Pressure_Pad_Leg_Data_Range) //小于腿部 20
	// 				{
	// 					Pressure_Pad_Leg_Flag = 1; //腿部超压
	// 				}
	// 				else if (Pressure_Pad_Leg_Data_Range < j &&
	// 						 j < (Pressure_Pad_Leg_Data_Range + Pressure_Pad_Hip_Data_Range)) // j大于20 小于30
	// 				{
	// 					Pressure_Pad_Hip_Flag = 1; // 臀部超压
	// 				}
	// 				else if ((Pressure_Pad_Leg_Data_Range + Pressure_Pad_Hip_Data_Range) < j &&
	// 						 j < (Pressure_Pad_Back_Data_Range + Pressure_Pad_Hip_Data_Range + Pressure_Pad_Leg_Data_Range)) //大于30小于40
	// 				{
	// 					Pressure_Pad_Back_Flag = 1; // 背部超压
	// 				}
	// 				else if ((Pressure_Pad_Shoulder_Data_Range + Pressure_Pad_Back_Data_Range + Pressure_Pad_Hip_Data_Range) < j &&
	// 						 j < (Pressure_Pad_Shoulder_Data_Range + Pressure_Pad_Back_Data_Range + Pressure_Pad_Hip_Data_Range + Pressure_Pad_Leg_Data_Range)) //大于40 小于60
	// 				{
	// 					Pressure_Pad_Shoulder_Flag = 1; // 肩部超压
	// 				}
	// 			}
	// 			else // 不压着就清零
	// 			{
	// 				Pressure_Pad_Shoulder_Flag = 0;
	// 				Pressure_Pad_Back_Flag = 0;
	// 				Pressure_Pad_Hip_Flag = 0;
	// 				Pressure_Pad_Leg_Flag = 0;
	// 			}
	// 		}
	// 	}
	// 	// ---------------------------Temp--------------------------------//
	// 	if (Pressure_Pad_Leg_Flag) //腿部超压
	// 	{
	// 	}
	// 	else if (Pressure_Pad_Hip_Flag) // 臀部超压
	// 	{
	// 	}
	// 	else if (Pressure_Pad_Back_Flag) // 背部超压
	// 	{
	// 	}
	// 	else if (Pressure_Pad_Shoulder_Flag) // 肩部超压
	// 	{
	// 	}
	// #endif
	return Status;
}

// TODO:根据超时阈值同时判断超压状态
/**
 * @function: Time_OverPressure_Status_Check
 * @brief: None
 * @return {*}
 * @author: lzc
 */
#ifdef Pressure_Pad_Manufacturers_160_Length
// 合计16行
uint32_t TimeBase_Back_Value = 0;
uint32_t TimeBase_Shoulder_Value = 0;
uint32_t TimeBase_Hip_Value = 0;
uint32_t TimeBase_Leg_Value = 0;

// 警告
char Status_Value = 0;
// 0 ：没有警告  1：有黄警告  2：有红警告
char Back_Warning_Flag = 0;
char Shoulder_Warning_Flag = 0;
char Hip_Warning_Flag = 0;
char Leg_Warning_Flag = 0;

#endif

#ifdef Pressure_Pad_Manufacturers_1500_Length
// 合计25行
uint32_t TimeBase_Back_Value = 0;
uint32_t TimeBase_Shoulder_Value = 0;
uint32_t TimeBase_Hip_Value = 0;
uint32_t TimeBase_Leg_Value = 0;

// 警告
char Status_Value = 0;
// 0 ：没有警告  1：有黄警告  2：有红警告
char Back_Warning_Flag = 0;
char Shoulder_Warning_Flag = 0;
char Hip_Warning_Flag = 0;
char Leg_Warning_Flag = 0;

#endif
void Time_OverPressure_Status_Check(uint8_t Shoulder_OverTime_Yellow, uint8_t Back_OverTime_Yellow, uint8_t Hip_OverTime_Yellow, uint8_t Leg_OverTime_Yellow,
									uint8_t Shoulder_OverTime_Red, uint8_t Back_OverTime_Red, uint8_t Hip_OverTime_Red, uint8_t Leg_OverTime_Red)
{
#if Pressure_Warning_Enable
	if (NewWarn_Flag)
	{
		Status_Value = Judge_Overpressure_Status((rx1_buff + 4),
												 SettingPARA.Shoulder_Yellow_Pressure_Threshold, 20,
												 SettingPARA.Back_Yellow_Pressure_Threshold, 20,
												 SettingPARA.Hip_Yellow_Pressure_Threshold, 0,
												 SettingPARA.Leg_Yellow_Pressure_Threshold, 0);
	}
	else
	{
		Status_Value = Judge_Overpressure_Status((rx1_buff + 4),
												 120, 16, 120, 16, 120, 31, 120, 16);
	}
#else
	Status_Value = Judge_Overpressure_Status((rx1_buff + 4),
											 40, 10, 40, 10, 0, 0, 0, 0);
#endif
	// 单点阈值-60 ==== 均值阈值-20
	// 肩部 无警报
	if ((Status_Value & 0x08) != 0x08)
	{
		Shoulder_Warning_Flag = 0;
		TimeBase_Shoulder_Value = SysTimeBase;
	}

	// 单点阈值-60 ==== 均值阈值-20
	// 背部 无警报
	if ((Status_Value & 0x04) != 0x04)
	{
		Back_Warning_Flag = 0;
		TimeBase_Back_Value = SysTimeBase;
	}

	// 单点阈值-60 ==== 均值阈值-20
	// 肩部 无警报
	if ((Status_Value & 0x02) != 0x02)
	{
		Hip_Warning_Flag = 0;
		TimeBase_Hip_Value = SysTimeBase;
	}

	// 单点阈值-60 ==== 均值阈值-20
	// 背部 无警报
	if ((Status_Value & 0x01) != 0x01)
	{
		Leg_Warning_Flag = 0;
		TimeBase_Leg_Value = SysTimeBase;
	}

	// 肩部大于1 Hour
	if (SysTimeBase - TimeBase_Shoulder_Value >= (1 * (60 * Shoulder_OverTime_Yellow)) + 1)
	{
		Shoulder_Warning_Flag = 1;
		// 肩部大于2 Hour
		if (SysTimeBase - TimeBase_Shoulder_Value >= (1 * (60 * Shoulder_OverTime_Red)) + 4)
		{
			Shoulder_Warning_Flag = 2;
		}
	}

	// 背部大于1 Hour
	if (SysTimeBase - TimeBase_Back_Value >= (1 * (60 * Back_OverTime_Yellow)) + 1)
	{
		Back_Warning_Flag = 1;
		// 背部大于2 Hour
		if (SysTimeBase - TimeBase_Back_Value >= (1 * (60 * Back_OverTime_Red)) + 4)
		{
			Back_Warning_Flag = 2;
		}
	}

	// 臀部大于1 Hour
	if (SysTimeBase - TimeBase_Hip_Value >= (1 * (60 * Hip_OverTime_Yellow)) + 1)
	{
		Hip_Warning_Flag = 1;
		// 臀部大于2 Hour
		if (SysTimeBase - TimeBase_Hip_Value >= (1 * (60 * Hip_OverTime_Red)) + 4)
		{
			Hip_Warning_Flag = 2;
		}
	}

	// 腿部大于1 Hour
	if (SysTimeBase - TimeBase_Leg_Value >= (1 * (60 * Leg_OverTime_Yellow)) + 1)
	{
		Leg_Warning_Flag = 1;
		// 腿部大于2 Hour
		if (SysTimeBase - TimeBase_Leg_Value >= (1 * (60 * Leg_OverTime_Red)) + 4)
		{
			Leg_Warning_Flag = 2;
		}
	}

	Warning_State.Warn_Back_Flag = Back_Warning_Flag;
	Warning_State.Warn_Shoulder_Flag = Shoulder_Warning_Flag;
	Warning_State.Warn_Hip_Flag = Hip_Warning_Flag;
	Warning_State.Warn_Leg_Flag = Leg_Warning_Flag;
}

/**
 * @function: PressValue_SendHandle
 * @brief: 压力数据发送服务函数  发送到ESP32 jun'ge
 * @return {*}
 * @author: lzc
 */
uint8_t Status = 0;
#define Date_Length 100
#define PressValue_Threshold 80 // 压力预警
#define Leg_PressValue_Threshold 100
void PressValue_SendHandle()
{
	uint8_t j, i;
	uint8_t Temp_Buffer[rx1_buffersize] = {0};
	uint8_t Send_Buffer[rx1_buffersize] = {0};
	uint8_t PressWave_Buffer[60] = {0};
	uint8_t Sum_Count = 0;
	uint16_t Sum_Value = 0;
	// uint8_t Sum_Leg = 0;
	// uint16_t Sum_Leg_Date = 0;

	uint16_t average;

	uint64_t CalibrationTime;

	if (0 == Flag.SendDataOn)
		return; // 时间校准之前不发

	CalibrationTime = calibration.AddTime + calibration.StandardTime;

// TODO: 实时判断状态
#if Pressure_Warning_Enable // 压力预警
	if (NewWarn_Flag)
	{
		Time_OverPressure_Status_Check(SettingPARA.Shoulder_Yellow_OverTime_Threshold,
									   SettingPARA.Back_Yellow_OverTime_Threshold,
									   SettingPARA.Hip_Yellow_OverTime_Threshold,
									   SettingPARA.Leg_Yellow_OverTime_Threshold,
									   SettingPARA.Shoulder_Red_OverTime_Threshold,
									   SettingPARA.Back_Red_OverTime_Threshold,
									   SettingPARA.Hip_Red_OverTime_Threshold,
									   SettingPARA.Leg_Red_OverTime_Threshold);
	}
	else
	{
		Time_OverPressure_Status_Check(0, 0, 0, 0,
									   0, 0, 0, 0);
	}
#else
	Time_OverPressure_Status_Check(0, 0, 0, 0,
								   0, 0, 0, 0);
#endif
	PressValue_buff[0] = 0xA5;
	PressValue_buff[1] = 0x5A;
	// 数据长度
	PressValue_buff[2] = (uint8_t)(Date_Length + 32);
	PressValue_buff[3] = (Date_Length + 32) >> 8; // 高8位

	// PressValue_buff[2] = (uint8_t)(32);
	// PressValue_buff[3] = (32) >> 8; //高8位

	PressValue_buff[4] = 0x00; // PressValue_buff[4]=0x01;//陶钧frame:0

	PressValue_buff[5] = (uint8_t)(CalibrationTime >> 0);
	PressValue_buff[6] = (uint8_t)(CalibrationTime >> 8);
	PressValue_buff[7] = (uint8_t)(CalibrationTime >> 16);
	PressValue_buff[8] = (uint8_t)(CalibrationTime >> 24);
	PressValue_buff[9] = (uint8_t)(CalibrationTime >> 32);
	PressValue_buff[10] = (uint8_t)(CalibrationTime >> 40);
	PressValue_buff[11] = (uint8_t)(CalibrationTime >> 48);
	PressValue_buff[12] = (uint8_t)(CalibrationTime >> 56);

	// 精简压力长度   从第13位开始  长度18为压力数据
	PressValue_buff[13] = 18;
	// 精简压力上报
	for (char j = 0; j < 60; j++) // 列
	{
		Sum_Count = 0;
		Sum_Value = 0;
		// Sum_Leg = 0;
		// Sum_Leg_Date = 0;
		for (char k = 0; k < 25; k++) // 累加计算
		{
			// 超过阈值进行累加
			if (rx1_buff[(60 * k + 4) + j] > PressValue_Threshold) // 帧头2+长度2+原始数据1500
			{
				Sum_Count++;
				Sum_Value += rx1_buff[(60 * k + 4) + j]; // 阈值求和

				// 腿部并且超过阈值
				// if (j < 15 && rx1_buff[(60 * k + 4) + j] > Leg_PressValue_Threshold)
				// {
				// Sum_Leg++;
				// Sum_Leg_Date += rx1_buff[(60 * k + 4) + j];
				// }
			}
		}
		// if (j < 15)
		// PressWave_Buffer[j] = Sum_Leg_Date / Sum_Leg;
		// else
		PressWave_Buffer[j] = Sum_Value / Sum_Count; // 阈值做平均
	}

	// 头 和 脚
	for (char i = 0; i < 6; i++) // 各取6个点的压力值
	{
		PressValue_buff[14 + i] = PressWave_Buffer[60 - (3 * i)];
		PressValue_buff[26 + i] = PressWave_Buffer[20 - (3 * i)];
	}

	// 背 和 臀
	for (char i = 0; i < 3; i++) // 各取3个点的压力值
	{
		PressValue_buff[20 + i] = PressWave_Buffer[40 - (3 * i)];
		PressValue_buff[23 + i] = PressWave_Buffer[30 - (3 * i)];
	}

	// 去除校验和帧头
	memcpy(Temp_Buffer, rx1_buff, rx1count - 4);		// 去掉尾部CRC4个字节
	memcpy(Send_Buffer, Temp_Buffer + 4, rx1count - 8); // 从
	// 复制一部分进行发送
	memcpy(&PressValue_buff[32], Send_Buffer, Date_Length);
	CRC_usart2send(PressValue_buff, Date_Length + 32); // 数据发向平台

	// CRC_usart2send(PressValue_buff, 32);

	memset(rx1_buff, 0, rx1count); // 清空rx1_buff
}
//-----------------------------------------------------------------//
// 函数名称： warn_hdl()
// 函数功能： 低压报警
// 返 回 值：
//-----------------------------------------------------------------//

char bugFixFlag = 0;

// uint8_t warn_1 = 0;
// uint8_t warn_2 = 0;

void warn_hdl()
{
	// uint8_t Beep_one_flg = 0;
	warn_para.LowPress_ON = CurrentPARA.powON;
	if (0 == warn_para.LowPress_ON) // 不报警
	{
		warn_para.LowPress_time = 0;
		CurrentPARA.warn_info = 0;

		//Charge_Complete_Flag = FALSE;
		Warning_time_s = 0;
		// warn_state = 0;
		Yellow_Flg_test1 = 0;
		count_Y_NoFlash = 1;
	}
	else // 报警状态
	{
		// if (!system_started)
		// {
		// 	if (page_home == Flag.PageNO)
		// 	{
		// 		// 显示“低压”
		// 		TFTLCD_Draw_RLE_Bitmap(289, 13, (const GUI_BITMAP *)&bmdiya_warn); // 显示 红色字“低压”

		// 		if ((CurrentPARA.air_pressure > (threshold - warn_deviation)))
		// 		{
		// 			// 气压达到正常值，显示正常
		// 			TFTLCD_Draw_RLE_Bitmap(289, 13, (const GUI_BITMAP *)&bmzhengchang_warn); // 显示 黑色字“正常”
		// 			system_started = TRUE; // 标记开机检测完成
		// 		}
				
		// 	}
		// 	else if(warn_para.LowPress_time == warn_LowPress_time)
		// 	{
		// 		system_started = TRUE; 
		// 		// TFTLCD_Fill(bodongleftime_x, bodongleftime_y, bodongleftime_x + 180, bodongleftime_y + 24, MY_BLUE);
		// 	}
			
		// }

		if (!Charge_Complete_Flag) // 第一次
		{
			if (CurrentPARA.air_pressure < (threshold - warn_deviation)) // 未充盈   warn_deviation=100
			{
				if (warn_para.LowPress_time == warn_LowPress_longtime_beep && Flag.PageNO != page_low_pressure)
				{
					// Flag.PageNO = page_low_pressure;
					// Yellow_Flg_test1 = 1; // 黄灯闪烁

					// beep_alarm(2);

					// Low_yellow_led_On();

					warn_state = 1;
					// warn_1 = 1;
					// warn_button = 2;
					// CurrentPARA.warn_info = (CurrentPARA.warn_info & 0xfc) | 0x01;

					// test_beep();
					// TFTLCD_Draw_RLE_Bitmap(0, 0, (const GUI_BITMAP *)&bmwarning_new);
				}

				// ; // CurrentPARA.warn_info=(CurrentPARA.warn_info&0xfc)|0x01;//演示，临时去掉未充盈告警
			}
			else if(CurrentPARA.air_pressure > (threshold - warn_deviation) && Power_stop_Flg == 2)// 第一次报警 低压->主界面 （充盈）
			{
					Yellow_Flg_test1 = 0; // 黄灯闪烁
					count_Y_NoFlash = 1;
					warn_state = 0;
					// warn_button = 0;
					stop_alarm();
					Beep_one_flg = 0;
					Flag.PageNO = page_home;
					warn_para.LowPress_time = 0;
					CurrentPARA.warn_info = 0;

					// Power_stop_Flg = 0;
					// warn_state_flg = 0;
					Power_off_time = 0;
			}
		}
		else // 充满过
		{
			// if (system_started == TRUE)
			// {
			// 	if (warn_para.LowPress_time == warn_LowPress_time) // 低压
			// 	{
			// 		CurrentPARA.warn_info = (CurrentPARA.warn_info & 0xfc) | 0x02; // 为什么怎么计算
			// 	}
			// }

			if (CurrentPARA.air_pressure < WARNING_THRESHOLD) // 低压报警条件
			{
				// if (system_started == TRUE)
				// {
				// 	if (warn_para.LowPress_time == warn_LowPress_time) // 低压
				// 	{
				// 		CurrentPARA.warn_info = (CurrentPARA.warn_info & 0xfc) | 0x02; // 为什么怎么计算
				// 	}
				// }

				if (Warning_time_s >= WARNING_DURATION) // 持续低压足够长时间&& warn_state != 0
				{
					// Flag.PageNO = page_low_pressure;
					// Yellow_Flg_test1 = 1; // 黄灯闪烁
					warn_state = 2;
					// warn_2 = 2;
					// beep_alarm(2);
				}
			}
			else
			{
				if (Warning_time_s >= WARNING_DURATION)
				{
					Low_yellow_led_Off();
					Yellow_Flg_test1 = 0; // 黄灯不闪烁
					warn_state = 0;
					// warn_button = 0;
					// stop_alarm();
					Beepstop_Flg = 0;
					// Beep_one_flg = 0;
					// Red_alarm_light_False();
					Warning_time_s = 0; // 重置低压时间
					warn_para.LowPress_time = 0;
					CurrentPARA.warn_info = 0;
					// if (page_low_pressure == Flag.PageNO)
					// {
					// 	Flag.PageNO = page_home;
					// }
						
					Flag.PageNO = page_home;

					Power_stop_Flg = 0;
					// warn_state_flg = 0;
					Power_off_time = 0;
				}
				else
				{
					// warn_state = 0;
					Warning_time_s = 0; // 仅在未达到 60s 时重置
					warn_para.LowPress_time = 0;
					CurrentPARA.warn_info = 0;
					Power_off_time = 0;
				}
			}
		}
	}
	// Low_pressure_alarm();
}

// void warn_hdl()
// {
// 	warn_para.LowPress_ON = CurrentPARA.powON;
// 	if (0 == warn_para.LowPress_ON) // 不报警
// 	{
// 		warn_para.LowPress_time = 0;
// 		CurrentPARA.warn_info = 0;
// 	}
// 	else // 报警状态
// 	{
// 		if (CurrentPARA.air_pressure < (threshold - warn_deviation)) // 未充盈   warn_deviation=100
// 		{
// 			if (warn_para.LowPress_time >= warn_LowPress_time) // 低压
// 			{
// 				CurrentPARA.warn_info = (CurrentPARA.warn_info & 0xfc) | 0x02; // 为什么怎么计算
// 			}
// 			else
// 				; // CurrentPARA.warn_info=(CurrentPARA.warn_info&0xfc)|0x01;//演示，临时去掉未充盈告警
// 		}
// 		else
// 		{
// 			warn_para.LowPress_time = 0;
// 			CurrentPARA.warn_info = 0;
// 		}
// 	}
// }
//-----------------------------------------------------------------//
// 函数名称： SendCalibrtion()  时间校准函数
// 函数功能： 发送校准   20S校准一次  给esp32
// 返 回 值：
//-----------------------------------------------------------------//
void SendCalibrtion()
{
	uint8_t c[6];
	if (calibration.CheckTimeCount > 0)
		return;
	if (0 == calibration.CheckTimeout)
		calibration.CheckTimeFlag = 0;

	if (0 == calibration.CheckTimeFlag)
	{
		c[0] = 0xa5;
		c[1] = 0x5a;
		c[2] = 6;
		c[3] = 0;
		c[4] = 0x20;
		c[5] = 0;
		//		usart2send(c,6);
		CRC_usart2send(c, 6);
		calibration.CheckTimeFlag = 1;
		calibration.CheckTimeout = check_timeout; // #define check_timeout 20 记时20S 校准一次
	}
}
//-----------------------------------------------------------------//
// 函数名称：  data主题
// 函数功能：  组包发送到ESP32转发
// 返 回 值：
//-----------------------------------------------------------------//
void SendHdl()
{
	uint8_t s[31] = {0};
	uint64_t CalibrationTime;
	if (0 == Flag.SendDataOn)
	{
		return; // 时间校准之前不发
	}

	CalibrationTime = calibration.AddTime + calibration.StandardTime;

	s[0] = 0xa5;
	s[1] = 0x5a;
	s[2] = 30;
	s[3] = 0;
	s[4] = 0x01; // s[4]=0;
	s[5] = (uint8_t)(CalibrationTime >> 0);
	s[6] = (uint8_t)(CalibrationTime >> 8);
	s[7] = (uint8_t)(CalibrationTime >> 16);
	s[8] = (uint8_t)(CalibrationTime >> 24);
	s[9] = (uint8_t)(CalibrationTime >> 32);
	s[10] = (uint8_t)(CalibrationTime >> 40);
	s[11] = (uint8_t)(CalibrationTime >> 48);
	s[12] = (uint8_t)(CalibrationTime >> 56);

	// s[13] = CurrentPARA.powON;
	// NOTE: 超压状态的更新
	Status = (Warning_State.Warn_Shoulder_Flag << 6) +
			 (Warning_State.Warn_Back_Flag << 4) +
			 (Warning_State.Warn_Hip_Flag << 2) +
			 (Warning_State.Warn_Leg_Flag << 0);
	s[13] = Status;
	s[14] = CurrentPARA.hight;			 // 身高
	s[15] = CurrentPARA.weight;			 // 体重
	s[16] = CurrentPARA.mode;			 // 模式
	s[17] = CurrentPARA.WaveCycle_lenth; // 波动周期长度
	s[18] = CurrentPARA.turn_mode;
	s[19] = CurrentPARA.TurnCycle_lenth; // 波动周期长度

	s[20] = (uint8_t)cycle_LeftTime; // s
	s[21] = cycle_LeftTime >> 8;
	s[22] = (uint8_t)turn_LeftTime; // s
	s[23] = turn_LeftTime >> 8;

	s[24] = CurrentPARA.air_column;			   // 气压
	s[25] = (uint8_t)CurrentPARA.air_pressure; // 空气气压
	s[26] = CurrentPARA.air_pressure >> 8;
	s[27] = CurrentPARA.inbed; // 在离床
	s[28] = CurrentPARA.body_moving;
	s[29] = CurrentPARA.warn_info; // 低压或者正常气压
	// s[30] = 0x55;	  										// TODO:测试数据上传
	s[30] = CurrentPARA.turn_status; // 翻身充气状态
									 //	s[30] = (uint8_t)threshold;		  // 预期压力
									 //	s[31] = (uint8_t)threshold >> 8;  // 预期压力
									 //	s[32] = (uint8_t)threshold >> 16; // 预期压力
									 //	s[33] = (uint8_t)threshold >> 24; // 预期压力

	//	usart2send(s,24);
	CRC_usart2send(s, 31); // 组包发送到ESP32转发
}

////-----------------------------------------------------------------//
////函数名称：发送警报数据（全部组包发）
////函数功能：
////返 回 值：
////-----------------------------------------------------------------//
void warn_data()
{
	uint8_t warn_buffer[7] = {0};

	warn_buffer[0] = 0xa5;
	warn_buffer[1] = 0x5a;

	if ((warn_state == 1) || (warn_state == 2))
	{
		// // 特殊按钮状态，重复发送三次 button 值
		// warn_buffer[2] = CurrentPARA.air_column;
		// warn_buffer[3] = button;
		// CRC_usart2send(warn_buffer, 4); //组包发送到ESP32转发
		// 正常状态下，发送具体的参数信息
		warn_buffer[2] = 3;
		warn_buffer[3] = 0;

		warn_buffer[4] = 0x55;

		warn_buffer[5] = warn_state;

		warn_buffer[6] = warn_button;

		CRC_usart2send(warn_buffer, 7); // 组包发送到ESP32转发
	}

	// uint8_t warn_buffer[11] = {0};
	// //	#define HUMANBODY_HEXDATA 1//选择
	// warn_buffer[0] = 0xa5;
	// warn_buffer[1] = Alarm_type;
	// warn_buffer[2] = 7;
	// warn_buffer[3] = CurrentPARA.air_column;
	// warn_buffer[4] = button;
	// warn_buffer[5] = button;
	// warn_buffer[6] = button;
	// // usart2send(warn_buffer, 7);		  // 数据发向平台  身高、体重数据
	// CRC_usart2send(warn_buffer, 7); //组包发送到ESP32转发
	// #else

	// sprintf(&info[0], "{\"time\":%lld,\"health\":%d,\"status\":{\"pressureMattress\":%d,\"controlBox\":%d,\"mattressBody\":%d}}",
	//	calibration.AddTime + calibration.StandardTime, health, pressureMattress, controlBox, mattressBody); //合并字符串
	// #endif
}

//-----------------------------------------------------------------//
// 函数名称：Health主题
// 函数功能：
// 返 回 值：
//-----------------------------------------------------------------//
void sendHealthInfo()
{
	uint8_t tempLenth;
	char info[110] = {0};
	uint8_t s[110 + 5];
	int8_t health = 0, mattressBody = 0, controlBox = 0, pressureMattress = 0;
	if (0 == Flag.SendDataOn)
		return;				   // 时间校准之前不发
	if (1 == Flag.PressSensOn) // 压力垫插上
	{
		if (pressTimeoutCnt > pressTimeout)
			pressureMattress = -1; // 压力垫插上超时不正常
		else
			pressureMattress = 1; // 压力垫状态正常
	}
	else
	{
		pressureMattress = 0; // 没插压力垫
	}

	if (CurrentPARA.powON == 1) // 开机
	{
		controlBox = 1; // 控制盒工作
	}
	else
	{
		controlBox = -1; // 控制盒不工作
	}

	if (gpio_input_bit_get(GPIOB, GPIO_PIN_1) == 0)
	{
		mattressBody = 1; // 气床垫体插上
	}
	else
	{
		mattressBody = 0; // 气床垫体插上
	}
	if (2 == CurrentPARA.warn_info) // 判断气柱是否插上等，低压预警
	{
		// controlBox = -1;//控制未开机
		// mattressBody = -1;//气床垫体未插上
	}
	if (-1 == controlBox || -1 == mattressBody || -1 == pressureMattress)
		health = -1; // 控制未开机  或者 气床垫体未插上  或者  压力垫插上不正常
	else
		health = 1;

	sprintf(&info[0], "{\"time\":%lld,\"health\":%d,\"status\":{\"pressureMattress\":%d,\"controlBox\":%d,\"mattressBody\":%d}}",
			calibration.AddTime + calibration.StandardTime, health, pressureMattress, controlBox, mattressBody); // 合并字符串

	tempLenth = strlen(&info[0]);

	s[0] = 0xA5;
	s[1] = 0x5A;
	s[2] = tempLenth + 1;
	s[3] = 0;
	s[4] = 0x40;						// 控制字
	memcpy(&s[5], &info[0], tempLenth); // 复制字符串到s中

	usart2send(s, tempLenth + 5); // 5
}

////-----------------------------------------------------------------//
////函数名称：发送身高 体重数据（全部组包发）  wifi增加主题
////函数功能：
////返 回 值：
////-----------------------------------------------------------------//
void sendhumanbody_data()
{
	uint8_t humanbody_buffer[11] = {0};
	//	#define HUMANBODY_HEXDATA 1//选择
	humanbody_buffer[0] = 0xa5;
	humanbody_buffer[1] = 0x5a;
	humanbody_buffer[2] = 7;
	humanbody_buffer[3] = 0;
	humanbody_buffer[4] = 0x60;
	humanbody_buffer[5] = CurrentPARA.hight;  // 身高
	humanbody_buffer[6] = CurrentPARA.weight; // 体重
	usart2send(humanbody_buffer, 7);		  // 数据发向平台  身高、体重数据
											  // #else

	// sprintf(&info[0], "{\"time\":%lld,\"health\":%d,\"status\":{\"pressureMattress\":%d,\"controlBox\":%d,\"mattressBody\":%d}}",
	//	calibration.AddTime + calibration.StandardTime, health, pressureMattress, controlBox, mattressBody); //合并字符串
	// #endif
}

//-----------------------------------------------------------------//
// 函数名称：版本号
// 函数功能：
// 返 回 值：
//-----------------------------------------------------------------//
void sendFirmwareInfo()
{
	uint8_t info[10];
	uint32_t value;
	value = *(__IO uint32_t *)FLASH_VERSION_ADDR; // 版本号

	info[0] = 0xA5;
	info[1] = 0x5A;
	info[2] = 10;
	info[3] = 0;
	info[4] = 0x30;
	info[5] = 0x01;
	info[6] = (uint8_t)value;
	info[7] = (uint8_t)(value >> 8);
	info[8] = (uint8_t)(value >> 16);
	info[9] = (uint8_t)(value >> 24);
	CRC_usart2send(info, 10); // 组包 向平台发
}

//-----------------------------------------------------------------//
// 函数名称：发送压力垫数据（全部组包发）    wifi增加主题
// 函数功能：为了测试翻身功能时，压力垫数据的内容
// 返 回 值：
//-----------------------------------------------------------------//
#define ALL_PRESS_DATASEND 1 // 选择全部发送压力数据或者分包发送数据
void sendpress_data()
{
	uint8_t press_Buffer[1500] = {0};
	uint8_t press_data1_Buffer[1505] = {0};
	uint8_t press_data1[750] = {0};
	uint8_t press_data2[750] = {0};
	uint16_t loop, c, f;
	c = 0;
// uint8_t length1 = sizeof(rx1_buff)/sizeof(uint8_t);
// 将数据存进press_Buffer  只能用于字符类型
#if ALL_PRESS_DATASEND
	memcpy(press_Buffer, &rx1_buff[3], 1500); // 去掉首部4个字节

	press_data1_Buffer[0] = 0xa5;
	press_data1_Buffer[1] = 0x5a;
	press_data1_Buffer[2] = 10;
	press_data1_Buffer[3] = 0x0;
	press_data1_Buffer[4] = 0x50;
	// press_data1_Buffer[5]=0xAA;
	// press_data1_Buffer[6]=0xBB;
	for (f = 0; f < 1500; f++)
	{
		press_data1_Buffer[c + 5] = press_Buffer[f];
		c++;
	}
	usart2send(press_data1_Buffer, 1505); // 组包压力垫数据发向平台

	// CRC_usart2send(press_Buffer, 1500); //数据发向平台
#else
	uint16_t e, d;
	e = d;
	for (loop = 0; loop < 1500; loop++)
	{
		if (loop < 750)
		{
			press_data1[e] = press_Buffer[loop];
			e++;
		}
		else
		{
			press_data2[d] = press_Buffer[loop];
			d++;
		}
	}
	CRC_usart2send(press_data1, 750); // 数据发向平台  压力数据前750个
	CRC_usart2send(press_data2, 750); // 数据发向平台  压力数据后750个
#endif
}
//-----------------------------------------------------------------//
// 函数名称：
// 函数功能：  组包发送到ESP32转发
// 返 回 值：
//-----------------------------------------------------------------//
void HealthSendHdl()
{
	; // 上面就有
}

//-----------------------------------------------------------------//
// 函数名称：
// 函数功能：波动 气柱充气
// 输入参数： 无
// 输出参数： 无
// 返 回 值：
//-----------------------------------------------------------------//
void ModeHdl()
{
	Pump1Work(threshold);			   // 充气工作
	if (CurrentPARA.mode == MODE_WAVE) // 判断模式是否波动模式
	{
		if (warn_state == 0 && 0 == cycle_LeftTime) // 换气剩余时间  warn_state == 0 &&
		{
			if (1 == CurrentPARA.air_column) // uint8_t air_column;	当前气柱 A 0X01 B 0X02 C 0X03(两根都充气)
			{
				CurrentPARA.air_column = 2; // 哪条气柱充气
				vave1_SetPosi = limit3;		// 3
			}
			else
			{
				CurrentPARA.air_column = 1;
				vave1_SetPosi = limit1; // 1
			}
			cycle_LeftTime = 60 * CurrentPARA.WaveCycle_lenth;
		}
	}

	//	if (CurrentPARA.air_column = 3)
	//	{
	//		uint16_t temp;
	//		temp = ADC_AirPress1();

	//		if (temp == 15000)
	//		{
	//			stop_flg = 1;//表示充气完成
	//		}
	//		else
	//		{
	//			stop_flg = 2;//表示充气未完成
	//		}
	//
	//	}
	//	stop_flg = 0;
	//
}

//-----------------------------------------------------------------//
// 函数名称：
// 函数功能：
// 输入参数： 无
// 输出参数： 无
// 返 回 值：
//-----------------------------------------------------------------//
/***************定时器中断****************************/
char count_Y_NoFlash = 1;

void TIMER5_IRQHandler()
{
	static uint16_t count_ms = 0;
	static uint16_t count_ms_500ms = 0;
	// static uint16_t Power_off_time = 0;

	// uint8_t warn_state_flg = 0;
	// static uint16_t Warning_time_s = 0;//Warning_time_m; //单位秒，预警时间10分钟 //目前两分钟
	//	uint8_t Air_Pressure_Completion_Flag = 0; //充气气压标志位

	calibration.AddTime++;
	if (adc_ReadTime1) // 50ms递减
		adc_ReadTime1--;
	if (adc_ReadTime2)
		adc_ReadTime2--;
	if (adc_ReadTime3)
		adc_ReadTime3--;
	if (adc_ReadTime4)
		adc_ReadTime4--;
	if (UartSendDelay) // 100ms延时
		UartSendDelay--;
	if (key_option_time)
		key_option_time--;
	//	if(SettingFlag.blinkOption_time) SettingFlag.blinkOption_time--;
	if (Flag.KeyKeepCnt)
		Flag.KeyKeepCnt--;
	if (Flag.LockCnt > 0) // 30000
		Flag.LockCnt--;
	if (Flag.wifiKey_time) // 1500
		Flag.wifiKey_time--;
	if (Flag.BeepKey_time) // 1500
		Flag.BeepKey_time--;

	if (count_ms_500ms++ > 250) // 500ms，2Hz/s
	{
		// if (gpio_input_bit_get(POWER_DETECT_GPIO, POWER_DETECT_PIN) == RESET)
		if(Power_stop_Flg == 1)
		{
			if (Red_Flg_test1 == 1) // 红灯闪烁
			{
				RED_FIG = !RED_FIG;
				if (RED_FIG == 0)
				{
					Red_alarm_light_Ture();
				}
				else
				{
					Red_alarm_light_False();
				}
			}
			else
			{
				Red_alarm_light_False();
			}
		}
		count_ms_500ms = 0; // 清零
	}

	if (count_ms++ > 1000) // 1s
	{
		if (calibration.CheckTimeCount > 0)
			calibration.CheckTimeCount--;
		if (1 == calibration.CheckTimeFlag)
		{
			if (calibration.CheckTimeout > 0)
				calibration.CheckTimeout--;
		}

		if (warn_para.LowPress_ON)
		{

			if (CurrentPARA.air_pressure > (threshold - warn_deviation) && Power_stop_Flg == 2) // 检查是否充气完成
			{
				Charge_Complete_Flag = TRUE; // FALSE：未完成，TURE：已完成
			}
			else if (CurrentPARA.air_pressure < (threshold - warn_deviation)) // 功能完成，已测试，功能正常
			{
				if (warn_para.LowPress_time < warn_LowPress_longtime_beep)
				{
					warn_para.LowPress_time++;
				}
			}

			if (Charge_Complete_Flag == TRUE) // 判断是否完成充气
			{
				if (CurrentPARA.air_pressure < WARNING_THRESHOLD) // 低压报警条件
				{
					if (Warning_time_s < WARNING_DURATION) // 避免溢出
					{
						Warning_time_s++;
					}
				}
			}
			// 功能：电机故障报警超时时间倒计时
			//  if (timer_2min > 0)
			//  {
			//  	timer_2min--;
			//  }

			// if (Flag.PageNO == page_low_pressure)
			// {
				if (Yellow_Flg_test1 == 1) // 黄灯闪烁
				{
					Yellow_FIG = !Yellow_FIG;
					if (Yellow_FIG == 0)
					{
						Low_yellow_led_On();
					}
					else
					{
						Low_yellow_led_Off();
					}
				}
				else
				{
					// Low_yellow_led_Off();
					if (count_Y_NoFlash)
						Low_yellow_led_Off();
					count_Y_NoFlash = 0;
				}
			// }

			// if (Flag.PageNO == page_low_pressure)
			// {
				if (Power_stop_Flg == 1)//断电
				{
					// warn_state = warn_state_flg;

					if (Power_off_time <= 33)
					{
						Power_off_time++;
					}
					
				}
			// }
			

			// if (Power_off_time <= 30)
			// {
			// 	if(Power_stop_Flg == 2)
			// 	{
			// 		warn_state_flg = warn_state;
			// 		Power_off_time = 0;
			// 		// Beep_one_flg = 0;
			// 		// warn_state_flg = 1;
			// 	}
					
			// }
			// else
			// {
			// 	warn_state = 0;
			// 	Power_off_time = 0;
			// 	warn_state_flg = 0;
			// 	Flag.PageNO = page_home;
			// }
			
		}

		if (cycle_LeftTime)
		{
			cycle_LeftTime--;

			//			if(cycle_LeftTime<320)	//演示debug
			//				warn_para.should_gravity=0;
		}
		if (turn_LeftTime)
		{
			turn_LeftTime--;

			//			if(turn_LeftTime<1670)	//演示debug
			//				warn_para.haunch_gravity=0;
		}

		if (1 == Flag.PressSensOn)
		{ // 插上压力垫无数据上传超时
			if (pressTimeoutCnt <= pressTimeout)
				pressTimeoutCnt++;
		}

		if (MODE_WAVE != CurrentPARA.mode) // 不波动持续时间    //有改动，需要测试
		{
			if (nowave_keeptime <= 362438) // 99小时99分99秒=362439，nowave_keeptime应设定时间减一秒,362439-1
			{
				nowave_keeptime++;
			}
			else
			{
				nowave_keeptime = 0;
				Flag.PageNO = page_lock;
			}

			//			if(nowave_keeptime>51) warn_para.should_gravity=1;//演示debug
		}
		// if (TURN_AUTO != CurrentPARA.turn_mode) // 不翻身持续时间
		// {
		// 	if (turn_keeptime <= 362438) // 99小时99分99秒，同上
		// 	{
		// 		turn_keeptime++;
		// 	}
		// 	else
		// 	{
		// 		turn_keeptime = 0;
		// 		Flag.PageNO = page_lock;
		// 	}

		//			if(turn_keeptime>126)	warn_para.haunch_gravity=1;//演示debug
		// }

		Flag.timer_1s = 1;
		SysTimeBase++;
		count_ms = 0; // 复位
	}

	if (Key_Struct.KeyScanFre++ > KeyScanTime) // #define KeyScanTime 20 // ms
	{
		Key_Struct.KeyScanFre = 0;
		Flag.KeyScanFlag = 1;
	}

	timer_flag_clear(TIMER5, TIMER_FLAG_UP);
}
/***************串口中断****************************/
//-----------------------------------------------------------------//
// 函数名称：
// 函数功能：
// 输入参数： 无
// 输出参数： 无
// 返 回 值：wifi
//-----------------------------------------------------------------//
void USART2_IRQHandler(void)
{
	static uint8_t rece_step = 0;
	uint16_t templen = 0;
	uint8_t receive;
	if (RESET != usart_interrupt_flag_get(USART2, USART_INT_FLAG_RBNE))
	{
		receive = (uint8_t)usart_data_receive(USART2);
		rx2_buff[rx2count++] = receive;
		if (rx2_frame_OK == 1) // 没处理完再发就丢弃
		{
			usart_data_receive(USART2);
			return;
		}
		switch (rece_step)
		{
		case 0:
			if (receive == 0xa5)
			{
				rece_step = 1;
				rx2count = 1;
			}
			else
				rx2count = 0;
			break;
		case 1:
			if (receive == 0x5a)
			{

				rx2_buff[0] = 0xa5;
				rx2_buff[1] = 0x5a;
				rx2count = 2;
				rece_step = 2;
			}
			else
			{
				if (receive == 0xA5)
				{
					rece_step = 1;
					rx2count = 1;
				}
				else
					rece_step = 0;
			}
			break;

		case 2:
			if (rx2count >= 4)
			{
				templen = (uint16_t)(rx2_buff[3]) << 8 | rx2_buff[2];
				if ((templen >= rx2_buffersize) || rx2count >= rx2_buffersize)
				{
					rece_step = 0;
					rx2count = 0;
				}
				if (rx2count >= (4 + templen))
				{
					rx2_frame_OK = 1;
					rece_step = 0;
				}
			}
			break;
		}
	}
}
//-----------------------------------------------------------------//
// 函数名称：
// 函数功能：串口1
// 输入参数： 无
// 输出参数： 无
// 返 回 值：压力垫
//-----------------------------------------------------------------//
void USART1_IRQHandler(void)
{
	// uint8_t dat;
	//        if (usart_interrupt_flag_get(USART1, USART_INT_FLAG_PERR) != RESET)
	//       {
	//         usart_interrupt_flag_clear(USART1, USART_INT_FLAG_PERR);
	//				//rx1_buff[0]=usart_data_receive(USART1);
	//				 usart_data_receive(USART1);
	//       }

	if (usart_interrupt_flag_get(USART1, USART_INT_FLAG_RBNE_ORERR) != RESET)
	{
		usart_interrupt_flag_clear(USART1, USART_INT_FLAG_RBNE_ORERR);
		// rx1_buff[0]=usart_data_receive(USART1);
		usart_data_receive(USART1);
	}

	//        if (usart_interrupt_flag_get(USART1, USART_INT_FLAG_ERR_FERR) != RESET)
	//       {
	//         usart_interrupt_flag_clear(USART1, USART_INT_FLAG_ERR_FERR);
	//				 //rx1_buff[0]=usart_data_receive(USART1);
	//				 usart_data_receive(USART1);
	//       }

	//        if (usart_interrupt_flag_get(USART1, USART_INT_FLAG_RBNE) != RESET)
	//       {
	//         usart_interrupt_flag_clear(USART1, USART_INT_FLAG_RBNE);
	//				 //rx1_buff[0]=usart_data_receive(USART1);
	//				 usart_data_receive(USART1);
	//       }

	// if(USART_GetITStatus(USART2, USART_IT_RXNE) != RESET)
	//        {
	//            USART_ClearFlag(USART2, USART_FLAG_RXNE);
	//            USART_ClearITPendingBit(USART2, USART_IT_RXNE);
	//            Data = USART_ReceiveData(USART2);
	//        }

	if (RESET != usart_interrupt_flag_get(USART1, USART_INT_FLAG_IDLE)) // 空闲中断+DMA
	{
		usart_interrupt_flag_clear(USART1, USART_INT_FLAG_IDLE); /* 清除空闲中断标志位 */
		// rx1_buff[0]=usart_data_receive(USART1);
		usart_data_receive(USART1);
		rx1count = rx1_buffersize - dma_transfer_number_get(DMA0, DMA_CH5); // 查询DMA写到那个位置
		dma_channel_disable(DMA0, DMA_CH5);									// 关闭DMA
		rx1_frame_OK = 1;													// 接收完成
																			// dma_transfer_number_config(DMA0, DMA_CH5, rx1_buffersize);    //采集数据，初始化  压力垫数据
																			// dma_channel_enable(DMA0, DMA_CH5);						      //使能DMA
	}
}
